package com.ruoyi.flow.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FlowListenerContainer {

    private static final Map<String, FlowListener> LISTENER_MAP = new HashMap<>();

    private static final FlowListener DEFAULT_FLOW_LISTENER = new InnerDefaultFlowListener();


    public static void register(String machineId, FlowListener flowListener) {
        LISTENER_MAP.put(machineId, flowListener);
    }

    public static FlowListener getListener(String machineId) {

        if (LISTENER_MAP.containsKey(machineId)) {
            return LISTENER_MAP.get(machineId);
        }

        for (String key : LISTENER_MAP.keySet()) {
            if (containsKey(key, machineId)) {
                return LISTENER_MAP.get(key);
            }
        }

        return DEFAULT_FLOW_LISTENER;

    }


    private static boolean containsKey(String mapKey, String listenerKey) {
        if (mapKey.contains("*")) {
            String regex = mapKey.replace("*", "[a-zA-Z0-9]+");
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(listenerKey);
            return matcher.matches();
        } else {
            return mapKey.equals(listenerKey);
        }
    }


}
